package com.huawei.classroom.student.h60;

import java.io.Closeable;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class ChatServer extends Thread{
	private int port;
	static String[] user;// 存放id和密码
	static List<ServerThread> ThreadList = new ArrayList<>();//存服务器线程数，后面需要群发消息
	/**
	 * 初始化 ， 根据情况适当抛出异常
	 * @param port
	 * @param passwordFilename 所有用户的用户名 口令
	 */
	//就只是收集port且对txt拆分
	public ChatServer (int port, String passwordFilename) throws IOException {
		 try {
			this.port = port;
			ChatServer.user = readFromTxt(passwordFilename).split("\r\n");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	/**
	 *  根据情况适当抛出异常
	 * 开始监听
	 */
	public void startListen( ) {
		start();
	}
	@Override
	public void run() {
		ServerSocket server = null;
		try {
			server = new ServerSocket(this.port);
			//int i = 3;
			while (true) {
				Socket socket = server.accept(); // 等待客户端连接，注意这种方式，可以和多个客户端建立连接
				//System.out.println("client " + socket.getInetAddress() + " connect ok!");
				ServerThread t = new ServerThread(socket);//每个客户有一个服务器线程
				ThreadList.add(t);
				t.start();//运行线程
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			close(server);
		}
	}
	
	//下面的别看了，读文件和关闭流的老套路
	private String readFromTxt(String filename) throws Exception {
		Reader reader = null;
		try {
			StringBuffer buf = new StringBuffer();
			char[] chars = new char[1024];
			// InputStream in=new FileInputStream(filename);

			reader = new InputStreamReader(new FileInputStream(filename), "UTF-8");
			int readed = reader.read(chars);
			while (readed != -1) {
				buf.append(chars, 0, readed);
				readed = reader.read(chars);
			}
			return buf.toString();
		} finally {
			close(reader);
		}
	}
	
	private void close(Closeable inout) {
		if (inout != null) {
			try {
				inout.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	 
}
